//
//  AbstractViewController.m
//  PandaGaming
//
//  Created by 裴烨烽 on 2017/10/26.
//  Copyright © 2017年 PPWhale. All rights reserved.
//

#import "AbstractViewController.h"

static char buttonActionBlockKey;
@interface AbstractViewController (){
    BOOL hasShowLogin;          /**< 判断是否登录*/
}
@property (nonatomic,strong)UIView *barTitleView;                   /**< navbar上面显示的View*/
@property (nonatomic,strong)UILabel *barMainTitleLabel;             /**< 标题*/
@property (nonatomic,strong)UILabel *barSubTitleLabel;              /**< 副标题*/
@property (nonatomic,strong)UIButton *absLeftButton;

@end

@implementation AbstractViewController

-(void)dealloc{
    PDLog(@"释放了");
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    if (self != [self.navigationController.viewControllers firstObject]){
        if (!([self isKindOfClass:[MainCenterBackViewController class]] || [self isKindOfClass:[MainCenterTopViewController class]])){
            [[PDMainTabbarViewController sharedController] setBarHidden:YES animated:YES];
        }
    } else {
        [[PDMainTabbarViewController sharedController] setBarHidden:NO animated:YES];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createBarTitleView];                      // 1. 创建navBar
    [self setupNavBarStatus];
    if (!self.hasCancelPanDismiss){
        [self.navigationController setEnableBackGesture:YES];
    } else {
        [self.navigationController setEnableBackGesture:NO];
    }
}

#pragma mark - 1. 创建navbar
- (void)createBarTitleView {
    _barTitleView = [[UIView alloc] initWithFrame:CGRectMake((kScreenBounds.size.width - BAR_TITLE_MAX_WIDTH) / 2., 0, BAR_TITLE_MAX_WIDTH, 44)];
    _barTitleView.backgroundColor = [UIColor clearColor];
    _barTitleView.clipsToBounds = YES;
    
    _barMainTitleLabel = [[UILabel alloc] initWithFrame:_barTitleView.bounds];
    _barMainTitleLabel.backgroundColor = [UIColor clearColor];
    _barMainTitleLabel.font = BAR_MAIN_TITLE_FONT;
    _barMainTitleLabel.adjustsFontSizeToFitWidth = YES;
    _barMainTitleLabel.textColor = [UIColor colorWithCustomerName:@"黑"];
    _barMainTitleLabel.text = @"";
    [_barTitleView addSubview:_barMainTitleLabel];
    
    _barSubTitleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _barSubTitleLabel.backgroundColor = [UIColor clearColor];
    _barSubTitleLabel.font = BAR_SUB_TITLE_FONT;
    _barSubTitleLabel.textColor = [UIColor colorWithCustomerName:@"白"];
    [_barTitleView addSubview:_barSubTitleLabel];
    
    self.navigationItem.titleView = _barTitleView;
}

- (void)setBarMainTitle:(NSString *)barMainTitle {
    _barMainTitle = [barMainTitle copy];
    _barMainTitleLabel.text = _barMainTitle;
    
    [_barMainTitleLabel sizeToFit];
    CGRect rect = _barMainTitleLabel.bounds;
    rect.size.width = MIN(rect.size.width, BAR_TITLE_MAX_WIDTH);
    _barMainTitleLabel.bounds = rect;
    
    [self resetBarTitleView];
}

- (void)resetBarTitleView {
    CGSize mainTitleSize = _barMainTitleLabel.bounds.size;
    CGSize subTitleSize = _barSubTitleLabel.bounds.size;
    
    CGFloat titleViewHeight = mainTitleSize.height + subTitleSize.height;
    if (_barMainTitle.length && _barSubTitle.length) {
        titleViewHeight += BAR_TITLE_PADDING_TOP;
    }
    
    _barTitleView.bounds = CGRectMake(0., 0., BAR_TITLE_MAX_WIDTH, titleViewHeight);
    if ([Tool isEmpty:_barSubTitle]) {
        if (titleViewHeight < 44) {
            titleViewHeight = 44;
        }
        _barTitleView.bounds = CGRectMake(0., 0., BAR_TITLE_MAX_WIDTH, titleViewHeight);
        _barMainTitleLabel.center = CGPointMake(BAR_TITLE_MAX_WIDTH*0.5, 22);

        // 移除
        for (UIView *view in self.navigationController.navigationBar.subviews){
            if ([view isKindOfClass:[HTHorizontalSelectionList class]]){
                [view removeFromSuperview];
            }
        }
    } else {
        _barMainTitleLabel.center = CGPointMake(BAR_TITLE_MAX_WIDTH*0.5, _barMainTitleLabel.bounds.size.height*0.5);
        _barSubTitleLabel.center = CGPointMake(BAR_TITLE_MAX_WIDTH*0.5, titleViewHeight - _barSubTitleLabel.bounds.size.height*0.5);
    }
}

#pragma mark - Button
- (void)hidesBackButton {
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = nil;
}

- (UIButton *)leftBarButtonWithTitle:(NSString *)title barNorImage:(UIImage *)norImage barHltImage:(UIImage *)hltImage action:(void(^)(void))actionBlock {
    UIButton *button = [self buttonWithTitle:title buttonNorImage:norImage buttonHltImage:hltImage];
    objc_setAssociatedObject(button, &buttonActionBlockKey, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    
    
    return button;
}

- (UIButton *)rightBarButtonWithTitle:(NSString *)title barNorImage:(UIImage *)norImage barHltImage:(UIImage *)hltImage action:(void(^)(void))actionBlock {
    UIButton *button = [self buttonWithTitle:title buttonNorImage:norImage buttonHltImage:hltImage];

    objc_setAssociatedObject(button, &buttonActionBlockKey, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = barButtonItem;
    
    return button;
}

- (UIButton *)buttonWithTitle:(NSString *)title buttonNorImage:(UIImage *)norImage buttonHltImage:(UIImage *)hltImage {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setImage:norImage forState:UIControlStateNormal];
    [button setImage:hltImage forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor colorWithCustomerName:@"黑"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithCustomerName:@"黑"]forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor colorWithCustomerName:@"黑"] forState:UIControlStateDisabled];
    [button addTarget:self action:@selector(actionButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    button.backgroundColor = [UIColor clearColor];
    button.titleLabel.font = BAR_BUTTON_FONT;
    [button sizeToFit];

    button.bounds = CGRectMake(0, 0, 44, 44);

    return button;
}

- (void)actionButtonClicked:(UIButton *)sender {
    void (^actionBlock) (void) = objc_getAssociatedObject(sender, &buttonActionBlockKey);
    actionBlock();
}

#pragma mark - TabBar
- (void)hidesTabBarWhenPushed {
    [self setHidesBottomBarWhenPushed:YES];
}

- (void)hidesTabBar:(BOOL)hidden animated:(BOOL)animated {
    UITabBarController *tabBarController = self.tabBarController;
    UITabBar *tabBar = tabBarController.tabBar;
    if (!tabBarController || (tabBar.hidden == hidden)) {
        return;
    }
    
    CGFloat tabBarHeight = tabBar.bounds.size.height;
    CGFloat adjustY = hidden ? tabBarHeight : -tabBarHeight;
    
    if (!hidden) {
        tabBar.hidden = NO;
    }
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:animated ? 0.3 : 0. animations:^{
        CGRect rect = tabBar.frame;
        rect.origin.y += adjustY;
        tabBar.frame = rect;
        
        for (UIView *view in tabBarController.view.subviews) {
            if ([NSStringFromClass([view class]) hasSuffix:@"TransitionView"]) {
                if (!IS_IOS7_LATER) {
                    CGRect rect = view.frame;
                    rect.size.height += adjustY;
                    view.frame = rect;
                }
                view.backgroundColor = weakSelf.view.backgroundColor;
            }
        }
    } completion:^(BOOL finished) {
        tabBar.hidden = hidden;
        CGRect rect = weakSelf.view.frame;
        rect.size.height += adjustY;
        weakSelf.view.frame = rect;
    }];
}

#pragma mark -
#pragma mark  NavigationBar
-(void)setupNavBarStatus{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithRenderColor:[UIColor whiteColor] renderSize:CGSizeMake(kScreenBounds.size.width, 64)] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    
    self.view.autoresizesSubviews = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.view.backgroundColor = BACKGROUND_VIEW_COLOR;
    //去掉navigationBar底部线
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    // navbar 左侧的按钮
    [self navBarLeftButtonStatus];
}

-(void)navBarLeftButtonStatus{
    __weak typeof(self)weakSelf = self;
    if (self != [self.navigationController.viewControllers firstObject]) {
      self.absLeftButton =  [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"icon_main_back"] barHltImage:[UIImage imageNamed:@"icon_main_back"] action:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    } else {
      self.absLeftButton =  [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"icon_home_slider"] barHltImage:[UIImage imageNamed:@"icon_home_slider"] action:^{
//            [[RESideMenu shareInstance] presentLeftMenuViewController];
        }];
    }

}

#pragma mark - OtherManager
-(NSInteger)cellIndexPathSectionWithcellData:(NSString *)string sourceArr:(NSArray *)array{
    NSInteger cellIndexPathOfSection = -1;
    for (int i = 0 ; i < array.count ; i++){
        NSArray *dataTempArr = [array objectAtIndex:i];
        for (int j = 0 ; j <dataTempArr.count; j++){
            id item = [dataTempArr objectAtIndex:j];
            if ([item isKindOfClass:[NSString class]]){
                NSString *itemString = (NSString *)item;
                if ([itemString isEqualToString:string]){
                    cellIndexPathOfSection = i;
                    break;
                }
            }
        }
    }
    return cellIndexPathOfSection;
}

-(NSInteger )cellIndexPathRowWithcellData:(NSString *)string sourceArr:(NSArray *)array{
    NSInteger cellRow = -1;
    for (int i = 0 ; i < array.count ; i++){
        NSArray *dataTempArr = [array objectAtIndex:i];
        for (int j = 0 ; j <dataTempArr.count; j++){
            id item = [dataTempArr objectAtIndex:j];
            if ([item isKindOfClass:[NSString class]]){
                NSString *itemString = (NSString *)item;
                if ([itemString isEqualToString:string]){
                    cellRow = j;
                    break;
                }
            }
        }
    }
    return cellRow;;
}




#pragma mark - 自动登录
- (void)authorizeWithCompletionHandler:(void(^)(BOOL successed))handler{
//    if ([[AccountModel sharedAccountModel] hasLoggedIn]){
//        handler(YES);
//    } else {
//        if ([Tool userDefaultGetWithKey:LoginType].length && [Tool userDefaultGetWithKey:LoginKey].length){
//            [[AccountModel sharedAccountModel] autoLoginWithBlock:^(BOOL successed) {
//                handler(successed);
//            }];
//        } else {
//            [StatusBarManager statusBarHidenWithText:@"请先进行登录"];
//            LoginViewController *loginMainViewController = [[LoginViewController alloc]init];
//            [loginMainViewController loginSuccess:^(BOOL success) {
//                if (success){
//                    handler(YES);
//                } else {
//                    handler(NO);
//                    [StatusBarManager statusBarHidenWithText:@"取消登录&登录失败"];
//                }
//            }];
//            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginMainViewController];
//            [[PDMainTabbarViewController sharedController] presentViewController:nav animated:YES completion:NULL];
//        }
//    }
}







@end
